//
//  XYHomeTableVC.swift
//  SinaWB_XY
//
//  Created by 小熊猫 on 15/10/9.
//  Copyright © 2015年 小熊猫. All rights reserved.
//

import UIKit

private let CELL_IDENTI = "CellReuseIdentifier"

class XYHomeTableVC: UITableViewController, XYPopViewDelegate {

    var titleButton : XYTitleButton?
    //若指定此参数，则返回ID小于或等于max_id的微博
    var max_id:Int = 0
    //若指定此参数，则返回ID比since_id大的微博
    var sine_id:Int = 0
    
    //初始化一个装frame模型的数组
    var dataArray:[XYHomeCellF] = [XYHomeCellF]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.backgroundColor = ColorDefine(r: 240, g: 240, b: 240)
        
        //添加barButtonItem的按钮
        loadBarButtonItem()
        
        //设置tableview
        loadTableView()
        
        self.tabBarItem.badgeValue = "10"

    }
    
    //添加barButtonItem的按钮
    private func loadBarButtonItem(){
        //控制器的左右按钮
        navigationItem.leftBarButtonItem=UIBarButtonItem.item("navigationbar_friendsearch",target: self, action: "push")
        navigationItem.rightBarButtonItem=UIBarButtonItem.item("navigationbar_pop", target: self, action: "push")
        //把微博刷新视图添加到nav上
        navigationController?.view.insertSubview(pullDownView, belowSubview: self.navigationController!.navigationBar)
        
        //添加控制器的tiitleView
       loadTileView()
    }
    
    //添加titleView
    private func  loadTileView(){
         //控制器的titleView
        let btn = XYTitleButton()
        
        navigationItem.titleView=btn.TitleButton((XYWebModel.loadUserAccount()?.screen_name)!)
       
        //titleView的点击事件
        btn.didTitleButton = {(titleButton) -> () in
            self.didTitleButton(titleButton)
        }
        
    }
    
    //Nav的push控制器方法
    @objc private func push(){
        printLog("Home跳转控制器")
    }
    
    //实现titleView的按钮点击事件
    @objc private func didTitleButton(titleButton:XYTitleButton){
        //修改按钮的状态
        titleButton.selected = !titleButton.selected
        //添加一个遮罩view
        loadBackView(titleButton)
    }
    
    //创建点击titleView后的弹出框
    private func loadBackView(titleButton:XYTitleButton){
        
               
        //创建灰色框里面的view
        let redView = UIView()
        redView.size = CGSizeMake(100, 100)
        redView.backgroundColor = UIColor.redColor()
        
        let popView = XYPopView(contenView: redView)
        popView.delegate = self
        popView.show(titleButton)
        
    }
    
    //实现pop的代理方法
    func PopViewWillDismiss() {
       
        let button = navigationItem.titleView as! UIButton
        button.selected = false
    }
    
    
    
    private func loadTableView(){
        //给tableview注册一个cell
        self.tableView.registerClass(XYHomeTableViewCell.self, forCellReuseIdentifier: CELL_IDENTI)
        //设置上拉加载的控件
        self.tableView.tableFooterView = self.pullUpView
        
        //设置下拉刷新的控件
        self.refreshControl = UIRefreshControl()
        self.refreshControl?.beginRefreshing()
        self.refreshControl?.addTarget(self, action: "loadWeiBoData", forControlEvents: UIControlEvents.ValueChanged)
        
        //给tableview取消下划线
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        //请求微博的数据
        loadWeiBoData()
    }
    
    //申请微博数据
    @objc private func loadWeiBoData(){
       //每次加载的时候都把这两个属性清零
        self.max_id = 0
        self.sine_id = 0
        
        //判断上拉加载的view是否在转,如果转就是上拉.没有转而且还请求数据,一定是上拉
        //如果两者都不是的话,就是第一次加载.但是第一次的话判断中的if let 将不会成立
        if pullUpView.isAnimating(){
            if let id_num = dataArray.last{
                
                self.max_id = id_num.status!.id - 1
            }
        }else{
            if let id_num = dataArray.first{
                
                self.sine_id = id_num.status!.id
//                printLog("first:\(id_num.id)")
            }
        }
        
        
        
        let token = XYWebModel.loadUserAccount()!.access_token!
        XYSessionManager.sharedManager.loadSinaWeibo(token, max_id: self.max_id,since_id:self.sine_id ) { (dict, error) -> () in
           
            if error != nil{
                printLog("请求微博失败:\(error)")
                //关闭控件
                self.endAllAnimating()

            }else{
                printLog("请求微博成功")

                
                //把请求数据中的数组从字典中取出来
                let statusArray = dict!["statuses"] as! [[String:AnyObject]]
                //创建一个临时数组
                var tempArray = [XYHomeCellF]()
                
                //遍历数组.把数组中存放的字典数据赋值给模型
                for statusDict in statusArray{
                    
                    //给数组中的字典进行初始化
                    let status = XYStatusesModel.init(dict: statusDict)
                    
                    //利用数据模型初始化一个frame模型
                    let statusF = XYHomeCellF()
                    
                    //这一步之后,就开始计算frame,调用XYHomeCellF的didSet方法
                    statusF.status = status
                 
                    //将遍历的模型添加到临时数组中
                    tempArray.append(statusF)
                    
                }
                
               
                //做判断.看请求的是什么数据,然后添加
                if self.pullUpView.isAnimating(){
                    //如果在执行foot的动画,就证明是上拉加载,添加到后面
                    self.dataArray = self.dataArray + tempArray
                }else{
                
                    //如果没有,就证明是下拉刷新,添加到前面
                    //判断dataArray是否有数据.有就执行下拉动画
                    if self.dataArray.count != 0 {
                        self.pullDownViewIsAnimating(tempArray.count)
                    }

                    //如果是第一次.哪里都无所谓
                    self.dataArray = tempArray + self.dataArray
                }
                
                self.tableView.reloadData()
                //关闭控件
                self.endAllAnimating()
            }
        }
    }
    
    //停止控件动画
    private func endAllAnimating(){
        self.pullUpView.stopAnimating()
        self.refreshControl?.endRefreshing()
    }
    
    //下拉刷新的view动画
    private func pullDownViewIsAnimating(count:Int){
        
        if pullDownView.hidden == false {return}//如果正在显示.就不执行后面
        
        pullDownView.text = count == 0 ? "没有微博" : "\(count)条微博"
        
        pullDownView.hidden = false
        
        pullDownView.y = CGRectGetMaxY(self.navigationController!.navigationBar.frame) - pullDownView.height
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.pullDownView.y = CGRectGetMaxY(self.navigationController!.navigationBar.frame)
            }) { (finish) -> Void in
                
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    self.pullDownView.y = CGRectGetMaxY(self.navigationController!.navigationBar.frame) - self.pullDownView.height
                    }, completion: { (finish) -> Void in
                        self.pullDownView.hidden = true
                })
                
        }
        
    }
    
    //懒加载上拉加载的控件
    private lazy var pullUpView:UIActivityIndicatorView = {
        //初始化为大菊花
        let  view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        return view
    }()
    
    //懒加载下拉刷新的控件
    private lazy var pullDownView:UILabel = {
        let downLabel = UILabel()
        downLabel.width = SCREENW
        downLabel.height = 35
        downLabel.backgroundColor = UIColor.orangeColor()
        
        //设置字体
        downLabel.text = "没有微博数据"
        downLabel.textColor = UIColor.whiteColor()
        downLabel.textAlignment = NSTextAlignment.Center
        downLabel.font = UIFont.systemFontOfSize(14)
        
        //隐藏label
        downLabel.hidden = true
        
        return downLabel
    }()

}
    
extension XYHomeTableVC{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let  cell = tableView.dequeueReusableCellWithIdentifier(CELL_IDENTI, forIndexPath: indexPath) as! XYHomeTableViewCell
        
        //给cell的模型属性赋值
        cell.homeCellModel = self.dataArray[indexPath.row]
        
        //判断是否是最后一条cell 并且没有执行动画就加载数据
        if indexPath.row == self.dataArray.count - 1 && !pullUpView.isAnimating(){
            //开始旋转
            pullUpView.startAnimating()
            loadWeiBoData()
        }
        
        return cell
        
    }
    
    //返回不同的行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return self.dataArray[indexPath.row].rowHeight
    }
    
}











